package com.bupt.liutong.front.sch.action;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.bupt.liutong.admin.core.base.BaseAction;
import com.bupt.liutong.admin.core.bo.RoleBo;
import com.bupt.liutong.admin.core.bo.UserBo;
import com.bupt.liutong.admin.core.form.UserForm;
import com.bupt.liutong.util.StringUtils;

public class UserAction extends BaseAction {
	
	private UserBo userBo;
	private RoleBo roleBo;
	
	@SuppressWarnings("deprecation")
	public ActionForward login(ActionMapping mapping,
			ActionForm form, HttpServletRequest request,
			HttpServletResponse response) {
		UserForm userForm = (UserForm) form;
		
		if (!userBo.validateKaptcha(request)) {
			request.setAttribute("error", "验证码错误");
			return mapping.findForward("loginFail");
		} else if(userBo.validateLogin(userForm)) {
			HttpSession session = request.getSession();
			userForm = userBo.getUserByName(userForm);
			session.setAttribute("userForm", userForm);
			roleBo.putRoleInfo(session, userForm);
			String redirectUrl = request.getParameter("redirectUrl");
			
			// handle cookie
			userBo.handleCookie(request, response);
			
			if(StringUtils.isEmpty(redirectUrl))
				return mapping.findForward("loginSuccess");
			else
				return new ActionForward("", redirectUrl, true, true);
		} else {
			request.setAttribute("error", "用户名或密码错误");
			return mapping.findForward("loginFail");
		}
	}
	
	public ActionForward logout(ActionMapping mapping,
			ActionForm form, HttpServletRequest request,
			HttpServletResponse response) {
		HttpSession session = request.getSession();
		session.removeAttribute("userForm");
		roleBo.removeRoleInfo(session);
		return mapping.findForward("logoutSuccess");
	}
	
	public ActionForward register(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) {
		UserForm userForm = (UserForm) form;
		if (!userBo.validateKaptcha(request)) {
			request.setAttribute("error", "验证码错误");
			return mapping.findForward("registerFail");
		} else if (userBo.register(userForm)) {
			return mapping.findForward("registerSuccess");
		} else {
			request.setAttribute("error", "用户名已存在");
			return mapping.findForward("registerFail");
		}
	}

	public void setUserBo(UserBo userBo) {
		this.userBo = userBo;
	}

	public void setRoleBo(RoleBo roleBo) {
		this.roleBo = roleBo;
	}
}
